package com.example.waimai;

import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.model.LatLng;
import com.example.waimai.HttpUtil.MyGet;
import com.example.waimai.HttpUtil.MyPost;
import com.example.waimai.context.UserInfoContext;
import com.example.waimai.eventInterface.FragmentEvent;
import com.example.waimai.pojo.Store;
import com.example.waimai.pojo.User;
import com.example.waimai.pojo.UserAddress;
import com.example.waimai.ui.dashboard.DashboardFragment;
import com.example.waimai.ui.dashboard.orderItemDashAdapter;
import com.example.waimai.ui.home.HomeFragment;
import com.example.waimai.ui.notifications.NotificationsFragment;
import com.example.waimai.util.LocationUtil;
import com.example.waimai.util.MyThreadPool;
import com.example.waimai.util.RequestPermissionUtil;
import com.example.waimaiandroid.R;
import com.example.waimaiandroid.map.ZdpMapView;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.NavDestination;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;

import static android.widget.Toast.LENGTH_SHORT;

public class MainActivity extends AppCompatActivity implements FragmentEvent {
    private  Boolean isFirst = true;

    private static MainActivity mainActivity;



    private Fragment isFragment;
    public TextView UserCurrentAdd;
    private LatLng userCurrent = null;
    private ImageView updateUserAddr = null;
    private NavController navController;

    public MainActivity(){
        mainActivity = this;
    }
    public static MainActivity getMainActivity(){
        return mainActivity;
    }


    private void initUserInfo(){
        Bundle extras = getIntent().getExtras();
        boolean isFirstToMain = extras.getBoolean("isFirstToMain");
        if(isFirstToMain){
      }else{
            // 不是第一次登录
            // 只需要从 SredPreferences 中拿数据即可
            SharedPreferences sharedPreferences = getSharedPreferences("UserInfo",MODE_PRIVATE);
            int userId = sharedPreferences.getInt("UserId", -1);
            if(userId != -1){
                UserInfoContext.mUser.setId(userId);
            }
            // 拿一下用户的地址信息。
        }

        // 开个线程获取一下用户的地址信息
        MyThreadPool.doJob(new Runnable() {
            @Override
            public void run() {
                String url = "getAllUserAddress";
                UserInfoContext.mUserAddress = (ArrayList<UserAddress>) MyPost.doPost(url,UserInfoContext.mUser.getId());
                if(UserInfoContext.mUserAddress != null){
                    Log.e("测试UserInfoContetxt",String.valueOf(UserInfoContext.mUserAddress.size()));
                }
                if(UserInfoContext.mUserAddress != null && UserInfoContext.mUserAddress.size() != 0){
                    UserInfoContext.userReceiveAddr = UserInfoContext.mUserAddress.get(0);
                }
            }
        });
    }

    // 获取 MapActivity 返回过来的数据
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if(requestCode == 0){
            if(resultCode == 1){
                // MapActivity 返回的数据
                UserCurrentAdd.setText(UserInfoContext.currentAddr.getAddress());
                // 进行查询
                MyThreadPool.doJob(new Runnable() {
                    @Override
                    public void run() {
                        String longitude = String.valueOf(UserInfoContext.currentLatLng.longitude);
                        String latitude = String.valueOf(UserInfoContext.currentLatLng.latitude);
                        Map<String,String> param = new HashMap<>();
                        param.put("longitude",longitude);
                        param.put("latitude",latitude);
                        HomeFragment.stores = (List<Store>) MyPost.doPost("getMissedStore",param);
                        Message msg = new Message();
                        msg.what = 2;
                        HomeFragment.handler.sendMessage(msg);
                    }
                });
                isFirst = false;
            }else if(resultCode == 2){
                // 从 Comment 返回的数据
                // 获取到返回的 position
                int position = data.getIntExtra("position", -1);
                DashboardFragment.setPinjiaButton(position);
            }
        }else if(requestCode == 1){

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length >0){
                    // 遍历结果 ，看是否全部授权了
                    for(int result : grantResults){
                        if(result != PackageManager.PERMISSION_GRANTED){
                            Toast.makeText(this,"需要获取到全部权限才可以运行程序",LENGTH_SHORT).show();
                            onDestroy();
                            return ;
                        }
                    }
                }else{
                    // 当 grantResults 的长度 <=0 说明发生了未知的错误
                    Toast.makeText(this,"发生未知错误", LENGTH_SHORT).show();
                    finish();
                    return ;
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mainActivity = this;
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 权限获取
        RequestPermissionUtil.requestPermission(this);

        // 先去获取一下用户的全部信息和 地址信息
        if(UserInfoContext.mUserAddress == null){
            initUserInfo();
        }
        BottomNavigationView navView = findViewById(R.id.nav_view);
        // Passing each menu ID as a set of Ids because each
        // menu should be considered as top level destinations.
        AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(
                R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications)
                .build();

        navController = Navigation.findNavController(this, R.id.nav_host_fragment);
        NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
        NavigationUI.setupWithNavController(navView, navController);
        Log.i("demo","我来看看log能不能输出");
        Intent intent = getIntent();
        if(intent != null){
            boolean toOrderList = intent.getBooleanExtra("toOrderList", false);
            if(toOrderList){
                // 调用 Nav 来跳转到 订单界面
                try{navController.navigate(R.id.home_to_orderList);}
                catch (Exception e){
                    System.out.println(e.getStackTrace());
                }
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        // 开启一次定位
        /*UserCurrentAdd = findViewById(R.id.UserCurrentAddr);
        if(isFirst && UserCurrentAdd != null){
            initPosition();
            isFirst =  false;
        }else{
        }*/
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if(NotificationsFragment.notificationsViewModel != null){
            NotificationsFragment.notificationsViewModel.getUserInfo().setValue(UserInfoContext.mUser);
        }
    }


    private void initPosition(){
        LocationClient mLocationClient = new LocationClient(getApplicationContext());
        LocationClientOption mOption = new LocationClientOption();
        mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        mOption.setCoorType("bd09ll");
        mOption.setScanSpan(0);
        mOption.setOpenGps(true);
        mOption.setLocationNotify(false);
        mOption.setIgnoreKillProcess(false);
        mOption.SetIgnoreCacheException(false);
        mOption.setWifiCacheTimeOut(5 * 60 * 1000);
        mOption.setEnableSimulateGps(false);
        mOption.setIsNeedAddress(true);
        mLocationClient.setLocOption(mOption);
        // 注册一个监听函数
        mLocationClient.registerLocationListener(new BDAbstractLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                UserCurrentAdd.setText(bdLocation.getAddrStr());
                userCurrent = new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
                UserInfoContext.currentLatLng = new LatLng(bdLocation.getLatitude(),bdLocation.getLongitude());
                MyThreadPool.doJob(new Runnable() {
                    @Override
                    public void run() {
                        String longitude = String.valueOf(UserInfoContext.currentLatLng.longitude);
                        String latitude = String.valueOf(UserInfoContext.currentLatLng.latitude);
                        Map<String,String> param = new HashMap<>();
                        param.put("longitude",longitude);
                        param.put("latitude",latitude);
                        HomeFragment.stores = (List<Store>) MyPost.doPost("getMissedStore",param);
                        Message msg = new Message();
                        msg.what = 2;
                        HomeFragment.handler.sendMessage(msg);
                    }
                });
                mLocationClient.stop();
            }
        });
        mLocationClient.start();
    }

    @Override
    public void onAttachFragment(@NonNull Fragment fragment) {
        super.onAttachFragment(fragment);
    }


    // 实现 HomeFragment 中组件事件监听处理的具体逻辑
    @Override
    public void onImageClickListener(View view) {

    }

    // 用户主页面 点击 商家
    @Override
    public void onItemClickListener(View view) {

    }

    /*private HomeFragmentCallBack homeFragmentCallBack = new HomeFragmentCallBack() {
        @Override
        public void AddrOnClick() {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(MainActivity.this,mapActivity.class));
            MainActivity.this.startActivity(intent);
        }
    };*/
}